package com.twf.partnerMatching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.twf.partnerMatching.common.ErrorCode;
import com.twf.partnerMatching.common.utils.Validator;
import com.twf.partnerMatching.exception.BusinessException;
import com.twf.partnerMatching.mapper.UserMapper;
import com.twf.partnerMatching.model.domain.User;
import com.twf.partnerMatching.model.vo.UserClearVO;
import com.twf.partnerMatching.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author player
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2023-10-08 13:28:15
 */

/**
 * 用户服务实现类*
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        //特殊字符检验
        if (!Validator.isValidString(userAccount)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账户包含特殊字符");
        }
        //密码与校验密码
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        //重复校验
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账户重复");
        }
        //加密密码
        String salt = UUID.randomUUID().toString().substring(0, 4);
        String encryptPassword = DigestUtils.md5DigestAsHex((userPassword + salt).getBytes());
        //插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setSalt(salt);
        user.setAvatarUrl("https://ui-avatars.com/api/?name=" + user.getUserAccount() + "&rounded=true");
        user.setUsername("用户" + userAccount);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "未能注册用户");
        }
        return user.getId();
    }

    @Override
    public UserClearVO userLogin(String userAccount, String userPassword) {
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        //特殊字符检验
        if (!Validator.isValidString(userAccount)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账户包含特殊字符");
        }
        //查询用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "未能查询到用户,用户可能未注册");
        }
        //获取盐
        String salt = user.getSalt();
        String encryptPassword = DigestUtils.md5DigestAsHex((userPassword + salt).getBytes());
        //密码与校验密码
        if (!encryptPassword.equals(user.getUserPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误，请重新输入");
        }
        //脱敏
        return new UserClearVO(user);
    }

    @Override
    public List<UserClearVO> searchUsersByTags(List<String> list) {
        if (list.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        for (String s : list) {
//            queryWrapper = queryWrapper.like("tags", s);
//        }
//        List<User> userList = userMapper.selectList(queryWrapper);
//        return userList.stream().map(UserClearVO::new).collect(Collectors.toList());
        Gson gson = new Gson();
        List<User> userList = this.list();
        return userList.stream().filter(user -> {
            String tags = user.getTags();
            if (StringUtils.isBlank(tags)) {
                return false;
            }
            Set<String> tempTagNameSet = gson.fromJson(tags, new TypeToken<Set<String>>() {
            }.getType());
            for (String tagName : list) {
                if (!tempTagNameSet.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(UserClearVO::new).collect(Collectors.toList());
    }
}




